<template>
  <div class="app-container">
    <!-- 搜索区域使用 transform 包裹 -->
    <el-collapse-transition>
      <el-card v-show="isFilterVisible" class="search-wapper">
        <div>
          <el-form
            ref="form"
            :model="orderData"
            :inline="true"
            label-width="90px"
          >
            <el-form-item label="供应商:">
              <el-input
                v-model="orderData.supplier"
                placeholder="请选择"
                readonly
                suffix-icon="el-icon-more"
                style="width: 230px"
              />
            </el-form-item>

            <el-form-item label="业务员:">
              <el-select
                v-model="orderData.salesPerson"
                placeholder="请选择"
                style="width: 150px"
              >
                <el-option
                  v-for="item in salesPersonOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="单据日期:">
              <el-date-picker
                v-model="orderData.orderDate"
                type="date"
                placeholder="选择日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                style="width: 150px"
              />
            </el-form-item>

            <el-form-item label="交货日期:">
              <el-date-picker
                v-model="orderData.deliveryDate"
                type="date"
                placeholder="选择日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                style="width: 150px"
              />
            </el-form-item>

            <el-form-item label="">
              <el-radio
                v-model="orderData.orderType"
                label="purchase"
                class="blue-radio"
              >购货</el-radio>
              <el-radio
                v-model="orderData.orderType"
                label="return"
                class="blue-radio"
              >退货</el-radio>
            </el-form-item>

            <el-form-item label="发货地址:">
              <el-select
                v-model="orderData.deliveryAddress"
                placeholder="请选择"
                style="width: 200px"
              >
                <el-option
                  v-for="item in addressOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <i class="el-icon-edit address-edit" />
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </el-collapse-transition>

    <!-- 操作按钮区域 -->
    <el-card>
      <div class="table-operations-wrapper">
        <div class="table-operations">
          <el-button
            type="primary"
            size="small"
            class="filter-trigger"
            @click="isFilterVisible = !isFilterVisible"
          >{{ isFilterVisible ? "收起" : "检索" }}
            <i
              :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
            />
          </el-button>
          <el-button size="small">商品记录</el-button>
          <el-button
            type="primary"
            size="small"
            class="primary-btn"
          >保存并新增</el-button>
          <el-button
            type="primary"
            size="small"
            class="primary-btn"
          >保存</el-button>
          <el-button size="small">批量导入</el-button>
          <el-button size="small">审核</el-button>
        </div>

        <!-- 购物单录入区域 -->
        <div class="shopping-entry">
          <!-- <div class="entry-buttons">
          <el-button class="circle-btn" icon="el-icon-s-order">
            购货订单草稿
          </el-button>
          <el-button class="circle-btn" icon="el-icon-s-order">
            购货订单明细录入
          </el-button>
        </div> -->

          <div class="attachment-info">
            <el-link type="primary" class="upload-link">
              <i class="el-icon-paperclip" /> 上传附件
            </el-link>
            <span class="order-number">单据编号: GHDD202503240001</span>
          </div>
        </div>
      </div>

      <!-- 商品表格区域 -->
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="50"
          align="center"
        />

        <el-table-column
          type="index"
          label="序号"
          width="50"
          align="center"
        />

        <el-table-column label="商品" width="200" align="center">
          <template slot="header">
            <div class="product-header">
              <span class="required-mark">*</span>商品 -
              <el-switch
                v-model="scanEnabled"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="扫描枪录入"
              />
            </div>
          </template>
          <template slot-scope="scope">
            <div
              class="product-select"
              @click="selectProduct(scope.$index, scope.row)"
            >
              {{ scope.row.productName || "点击选择商品" }}
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="productImage"
          label="商品图片"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.productImage" class="product-image">
              <img :src="scope.row.productImage" alt="商品图片">
            </div>
            <i
              v-else
              class="el-icon-picture-outline"
              style="font-size: 20px; color: #909399"
            />
          </template>
        </el-table-column>

        <el-table-column
          prop="brand"
          label="品牌"
          width="100"
          align="center"
        />

        <el-table-column
          prop="productRemark"
          label="商品备注"
          width="120"
          align="center"
          show-overflow-tooltip
        />

        <el-table-column
          prop="attribute"
          label="属性"
          width="100"
          align="center"
        />

        <el-table-column
          prop="unit"
          label="单位"
          width="80"
          align="center"
        />

        <el-table-column label="仓库" width="120" align="center">
          <template slot="header">
            <div class="batch-header">
              <span class="required-mark">*</span>仓库
              <span class="batch-tag">批</span>
            </div>
          </template>
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.warehouse"
              placeholder="请选择"
              size="small"
            >
              <el-option
                v-for="item in warehouseOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="可用库存" width="100" align="center">
          <template slot="header">
            <div class="info-header">
              可用库存
              <i class="el-icon-question" />
            </div>
          </template>
          <template slot-scope="scope">
            {{ scope.row.availableStock || "0" }}
          </template>
        </el-table-column>

        <el-table-column label="数量" width="120" align="center">
          <template slot="header">
            <div class="batch-header">
              <span class="required-mark">*</span>数量
              <span class="batch-tag">批</span>
            </div>
          </template>
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.quantity"
              :min="0"
              :precision="2"
              size="small"
              controls-position="right"
              @change="calculateTotal"
            />
          </template>
        </el-table-column>

        <el-table-column label="批号" width="120" align="center">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.batchNumber"
              placeholder="请输入"
              size="small"
            />
          </template>
        </el-table-column>

        <el-table-column label="整件散包" width="120" align="center">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.packageType"
              placeholder="请选择"
              size="small"
            >
              <el-option label="整件" value="whole" />
              <el-option label="散包" value="loose" />
            </el-select>
          </template>
        </el-table-column>
      </el-table>

      <!-- 合计行 -->
      <div class="summary-row">
        <div class="summary-label">合计:</div>
        <div style="flex-grow: 1" />
        <div style="margin-right: 15px">数量: {{ totalQuantity }}</div>
      </div>

      <!-- 备注区域 -->
      <div class="remark-container" style="margin-top: 20px">
        <el-input
          v-model="orderData.remark"
          type="textarea"
          :rows="2"
          placeholder="备注信息"
        />
      </div>

      <!-- 金额信息区域 -->
      <div class="amount-container">
        <div class="amount-row">
          <div class="amount-item">
            <span class="amount-label">优惠率(%):</span>
            <el-input
              v-model="orderData.discountRate"
              class="amount-input"
            />
          </div>

          <div class="amount-item">
            <span class="amount-label">优惠金额:</span>
            <el-input
              v-model="orderData.discountAmount"
              class="amount-input"
            />
          </div>

          <div class="amount-item">
            <span class="amount-label">优惠后金额:</span>
            <el-input
              v-model="orderData.discountedAmount"
              class="amount-input"
              readonly
            />
          </div>

          <div class="amount-item">
            <span class="amount-label">交货方式:</span>
            <el-select
              v-model="orderData.deliveryMethod"
              placeholder="请选择"
              class="amount-input wider"
            >
              <el-option
                v-for="item in deliveryMethodOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
      </div>

      <!-- 底部工具栏 -->
      <div class="footer-toolbar">
        <div class="custom-field">
          <el-link type="primary" class="blue-text">
            <i class="el-icon-plus" /> 自定义字段
          </el-link>
        </div>

        <div class="history-buttons">
          <el-button
            size="small"
            class="history-btn"
            @click="handleHistory"
          >历史单据</el-button>
          <el-button size="small" class="history-btn">操作日志</el-button>
        </div>
      </div>

      <!-- 分页组件 -->
      <el-row
        v-if="false"
        :gutter="10"
        style="margin-top: 20px"
        type="flex"
        justify="end"
      >
        <el-pagination
          background
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </el-card>

    <!-- 商品选择弹窗 -->
    <el-dialog
      title="选择商品"
      :visible.sync="productDialogVisible"
      width="80%"
      append-to-body
    >
      <div class="product-dialog-content">
        <!-- 搜索区域 -->
        <div class="search-bar">
          <el-tabs v-model="activeTab" class="product-tabs">
            <el-tab-pane label="商品" name="product">
              <div class="tab-content">
                <el-input
                  v-model="productQuery.keyword"
                  placeholder="请输入商品编号/名称/型号/品牌"
                  style="width: 250px"
                  clearable
                >
                  <template slot="prepend">商品</template>
                </el-input>
                <el-select
                  v-model="productQuery.warehouse"
                  placeholder="仓库"
                  style="width: 120px"
                  clearable
                >
                  <el-option
                    v-for="item in warehouseOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-checkbox
                  v-model="productQuery.hasInventory"
                >零库存商品</el-checkbox>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  @click="searchProducts"
                >查询</el-button>
                <el-button @click="handleCommonProducts">常用商品</el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane label="近期交易" name="recent">
              <div class="tab-content">
                <!-- 近期交易搜索条件 -->
                <el-input
                  v-model="recentQuery.keyword"
                  placeholder="请输入商品编号/名称"
                  style="width: 250px"
                  clearable
                >
                  <template slot="prepend">商品</template>
                </el-input>
                <el-date-picker
                  v-model="recentQuery.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 260px"
                />
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  @click="searchRecentProducts"
                >查询</el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 商品列表区域 -->
        <div class="product-content">
          <div class="product-table">
            <el-table
              :data="productList"
              border
              style="width: 100%"
              height="400"
              @selection-change="handleProductSelectionChange"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="图片" width="80" align="center">
                <template slot-scope="scope">
                  <el-image
                    v-if="scope.row.productImage"
                    :src="scope.row.productImage"
                    :preview-src-list="[scope.row.productImage]"
                    style="width: 50px; height: 50px"
                  />
                  <i
                    v-else
                    class="el-icon-picture-outline"
                    style="font-size: 20px; color: #909399"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="productCode"
                label="商品编号"
                width="120"
              />
              <el-table-column prop="brand" label="品牌" width="100" />
              <el-table-column
                prop="productName"
                label="商品名称"
                min-width="200"
                show-overflow-tooltip
              />
              <el-table-column prop="specification" label="规格" width="100" />
              <el-table-column
                prop="unit"
                label="单位"
                width="80"
                align="center"
              />
              <el-table-column
                prop="availableStock"
                label="可用库存"
                width="100"
                align="right"
              />
              <el-table-column
                prop="purchasePrice"
                label="采购价"
                width="100"
                align="right"
              />
            </el-table>
          </div>

          <!-- 商品分类树 -->
          <div class="category-tree">
            <el-tree
              :data="categoryTree"
              :props="defaultProps"
              default-expand-all
              highlight-current
              @node-click="handleNodeClick"
            />
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            :current-page="productQuery.page"
            :page-sizes="[20, 50, 100]"
            :page-size="productQuery.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="productDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="confirmSelectProducts"
        >选中并关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'PurchaseDorder',
  data() {
    return {
      isFilterVisible: false, // 控制筛选区域显示/隐藏
      scanEnabled: false,
      orderData: {
        supplier: '',
        salesPerson: '',
        orderDate: '2025-03-24',
        deliveryDate: '2025-03-24',
        orderType: 'purchase',
        deliveryAddress: '',
        remark: '',
        discountRate: '0',
        discountAmount: '0',
        discountedAmount: '0.00',
        deliveryMethod: ''
      },
      salesPersonOptions: [
        { value: 'admin', label: '管理员' },
        { value: 'zhangsan', label: '张三' },
        { value: 'lisi', label: '李四' }
      ],
      addressOptions: [
        { value: 'address1', label: '广州市天河区某某路123号' },
        { value: 'address2', label: '深圳市南山区某某路456号' }
      ],
      deliveryMethodOptions: [
        { value: 'express', label: '快递' },
        { value: 'self', label: '自提' },
        { value: 'delivery', label: '送货' }
      ],
      warehouseOptions: [
        { value: 'warehouse1', label: '主仓库' },
        { value: 'warehouse2', label: '次仓库' }
      ],
      tableData: [
        {
          id: 1,
          productName: '',
          productImage: '',
          brand: '',
          productRemark: '',
          attribute: '',
          unit: '',
          warehouse: '',
          availableStock: 0,
          quantity: 0,
          batchNumber: '',
          packageType: 'whole'
        },
        {
          id: 2,
          productName: '',
          productImage: '',
          brand: '',
          productRemark: '',
          attribute: '',
          unit: '',
          warehouse: '',
          availableStock: 0,
          quantity: 0,
          batchNumber: '',
          packageType: 'whole'
        },
        {
          id: 3,
          productName: '',
          productImage: '',
          brand: '',
          productRemark: '',
          attribute: '',
          unit: '',
          warehouse: '',
          availableStock: 0,
          quantity: 0,
          batchNumber: '',
          packageType: 'whole'
        },
        {
          id: 4,
          productName: '',
          productImage: '',
          brand: '',
          productRemark: '',
          attribute: '',
          unit: '',
          warehouse: '',
          availableStock: 0,
          quantity: 0,
          batchNumber: '',
          packageType: 'whole'
        },
        {
          id: 5,
          productName: '',
          productImage: '',
          brand: '',
          productRemark: '',
          attribute: '',
          unit: '',
          warehouse: '',
          availableStock: 0,
          quantity: 0,
          batchNumber: '',
          packageType: 'whole'
        }
      ],
      totalQuantity: 0,
      multipleSelection: [],
      // 分页相关
      listQuery: {
        page: 1,
        limit: 20
      },
      total: 0,
      // 商品选择弹窗相关数据
      productDialogVisible: false,
      activeTab: 'product',
      productQuery: {
        keyword: '',
        warehouse: '',
        hasInventory: false,
        page: 1,
        limit: 20
      },
      recentQuery: {
        keyword: '',
        dateRange: [],
        page: 1,
        limit: 20
      },
      productList: [],
      selectedProducts: [],
      categoryTree: [
        {
          label: '全部',
          children: [
            {
              label: '茶',
              children: [{ label: '绿茶' }, { label: '红茶' }]
            },
            {
              label: '酒类',
              children: [{ label: '啤酒' }, { label: '葡萄酒' }]
            },
            {
              label: '饮料',
              children: [{ label: '果汁' }, { label: '矿泉水' }]
            }
          ]
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      currentEditIndex: -1,
      currentEditRow: null
    }
  },
  methods: {
    // 历史单据
    handleHistory() {
      this.$router.push({
        name: 'PurchaseReturnOrderHistoricalDocuments'
      })
    },
    // 打开商品选择弹窗
    selectProduct(index, row) {
      this.productDialogVisible = true
      this.currentEditIndex = index
      this.currentEditRow = row
      this.getProductList()
    },

    // 获取商品列表
    getProductList() {
      // TODO: 调用接口获取商品列表
      this.productList = [
        {
          productCode: 'SP0001',
          productName: '巧克力',
          brand: '费列罗',
          specification: '200g',
          unit: '盒',
          availableStock: 100,
          purchasePrice: 58.0
        }
        // ... 更多商品数据
      ]
    },

    // 搜索商品
    searchProducts() {
      this.productQuery.page = 1
      this.getProductList()
    },

    // 搜索近期交易商品
    searchRecentProducts() {
      // TODO: 实现近期交易商品搜索
      this.$message.info('搜索近期交易商品')
    },

    // 常用商品
    handleCommonProducts() {
      this.$message.info('加载常用商品列表')
    },

    // 商品选择变更
    handleProductSelectionChange(val) {
      this.selectedProducts = val
    },

    // 确认选择商品
    confirmSelectProducts() {
      if (this.selectedProducts.length === 0) {
        this.$message.warning('请选择商品')
        return
      }

      // 将选中的商品添加到表格
      this.selectedProducts.forEach((product) => {
        this.$set(
          this.tableData[this.currentEditIndex],
          'productName',
          product.productName
        )
        this.$set(
          this.tableData[this.currentEditIndex],
          'productImage',
          product.productImage
        )
        this.$set(
          this.tableData[this.currentEditIndex],
          'brand',
          product.brand
        )
        this.$set(this.tableData[this.currentEditIndex], 'unit', product.unit)
        this.$set(
          this.tableData[this.currentEditIndex],
          'availableStock',
          product.availableStock
        )
      })

      this.productDialogVisible = false
    },

    // 分类树节点点击
    handleNodeClick(data) {
      this.productQuery.category = data.label
      this.searchProducts()
    },

    // 计算总数量
    calculateTotal() {
      this.totalQuantity = this.tableData.reduce((sum, item) => {
        return sum + (Number(item.quantity) || 0)
      }, 0)
    },

    // 表格复选框选择
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 分页相关方法
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.search-wapper {
  margin-bottom: 15px;
}
.table-operations-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.table-operations {
  margin-bottom: 15px;
}

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

.shopping-entry {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  align-items: center;
}

.entry-buttons {
  display: flex;
}

.circle-btn {
  margin-right: 10px;
  border-radius: 20px;
}

.attachment-info {
  display: flex;
  align-items: center;
}

.upload-link {
  margin-right: 15px;
}

.product-header {
  display: flex;
  align-items: center;
}

.required-mark {
  color: #f56c6c;
  margin-right: 4px;
}

.product-select {
  color: #409eff;
  cursor: pointer;
}

.product-image {
  width: 50px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.product-image img {
  max-width: 100%;
  max-height: 100%;
}

.batch-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.batch-tag {
  background-color: #909399;
  color: white;
  font-size: 10px;
  padding: 0 4px;
  border-radius: 2px;
}

.info-header {
  display: flex;
  align-items: center;
}

.info-header .el-icon-question {
  margin-left: 4px;
  color: #909399;
  cursor: help;
}

/* 合计行 */
.summary-row {
  display: flex;
  background-color: #fdf6ec;
  padding: 10px 15px;
  font-weight: bold;
  border: 1px solid #ebeef5;
  border-top: none;
}

.summary-label {
  width: 50px;
}

/* 备注区域 */
.remark-container {
  margin-bottom: 20px;
}

/* 金额信息区域 */
.amount-container {
  margin-bottom: 20px;
}

.amount-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.amount-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 10px;
}

.amount-label {
  white-space: nowrap;
  margin-right: 5px;
  width: 80px;
  text-align: right;
}

.amount-input {
  width: 120px;
}

.amount-input.wider {
  width: 150px;
}

/* 底部工具栏 */
.footer-toolbar {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.blue-text {
  color: #409eff;
}

.history-buttons .history-btn {
  margin-left: 10px;
}

.blue-radio.el-radio ::v-deep .el-radio__input.is-checked + .el-radio__label {
  color: #409eff;
}

.address-edit {
  margin-left: 5px;
  cursor: pointer;
  color: #409eff;
}

.product-dialog-content {
  .search-bar {
    margin-bottom: 15px;
  }

  .product-tabs {
    .tab-content {
      padding: 15px 0;
      display: flex;
      gap: 10px;
      align-items: center;
    }
  }

  .product-content {
    display: flex;
    gap: 20px;
    margin-bottom: 15px;

    .product-table {
      flex: 1;
    }

    .category-tree {
      width: 200px;
      border-left: 1px solid #ebeef5;
      padding-left: 15px;
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>
